import Qs from 'qs'
import axios from 'axios'
import { checkProduct } from '@/assets/js/utils'

export default ({ app, store, req, env }, inject) => {
    let sessionTicket = ''
    let gettingSessionTicket = false
    let getSessionTicketTimes = 0
    /** 捕获异常捕获 */
    // process.on('unhandledRejection', ...error => {
    //   console.log('接口异常:', error);
    // });

    // 删除某个路径下的cookie
    // function removeCookiePath(name,path){
    //     let date=new Date();

    //     date.setTime(date.getTime()-10000);
    //     document.cookie=name+"=; expire="+date.toGMTString()+"; path="+path;
    // }
    function getEnvUrl() {
        if (!process.server) {
            return checkProduct()
                ? '//mp-api.zsdx.cn/hire'
                : '//gt4api.wxhand.com/hire'
        }
        return ''
    }
    /** 清除现有ticket */
    function clearSessionTicket() {
        sessionTicket = ''
        store.commit('ticket/SET_TICKET', '')
        if (!process.server) {
            localStorage.sessionTicket = sessionTicket
            // document.cookie = 'zdSessionTicket=;path=/'
        }
    }

    function getSessionTicket() {
        return sessionTicket
    }

    function setSessionTicket(ticket, sotrage = false) {
        sessionTicket = ticket
        // 本地存储
        store.commit('ticket/SET_TICKET', ticket)
        if (!process.server) {
            // document.cookie = 'zdSessionTicket=' + ticket + ';path=/'
            localStorage.sessionTicket = sessionTicket
        }
    }

    /** 获取本地ticket, vuex */
    function getSessionTicketLocal() {
        // if(!localStorage.hasClear)
        sessionTicket = localStorage.sessionTicket
        // 首次请求将vuex中的ticket重新写入cookie,防止cookie中的ticket过期,服务端重新获取
        if (!process.server) {
            // document.cookie = 'zdSessionTicket=' + sessionTicket + ';path=/'
            localStorage.sessionTicket = sessionTicket
        }

        return sessionTicket
    }

    /** 请求新的ticket */
    function getSessionTicketRemote() {
        return new Promise((resolve, reject) => {
            if (getSessionTicketTimes > 3) {
                reject(new Error('服务器错误，请稍后重试'))
                return
            }
            gettingSessionTicket = true
            app.$axios
                .$post(getEnvUrl() + '/Basic/createSessionTicket')
                .then((res) => {
                    // console.log(res);
                    if (res.code == 1) {
                        sessionTicket = res.data.session_ticket
                        // 本地存储
                        store.commit('ticket/SET_TICKET', sessionTicket)
                        setSessionTicket(sessionTicket)
                        if (!process.server) {
                            // document.cookie =
                            //     'zdSessionTicket=' + sessionTicket + ';path=/'
                            localStorage.sessionTicket = sessionTicket
                        }
                    } else {
                        console.log('获取sessionTicket失败')
                    }
                    gettingSessionTicket = false
                    getSessionTicketTimes++
                    resolve(sessionTicket)
                })
                .catch(() => {
                    gettingSessionTicket = false
                    getSessionTicketTimes++
                    // 并未超出次数, 稍后重试
                    resolve(sessionTicket)
                })
        })
    }
    function post(url, data) {
        if (url.indexOf('http') !== 0 && url.indexOf('//') !== 0) {
            if (!process.server) {
                url = getEnvUrl() + url
            }
        }
        // console.log('getNew url', url)
        return new Promise((resolve, reject) => {
            if (gettingSessionTicket) {
                console.log('gettingSessionTicket')
                setTimeout(function() {
                    post(url, data)
                        .then((resp) => resolve(resp))
                        .catch((resp) => reject(resp))
                }, 200)
                return
            }
            getSessionTicketLocal()
            // ticket空则重新获取,成功后重新请求
            if (!sessionTicket) {
                console.log('获取远程sessiontiekct')
                getSessionTicketRemote()
                    .then((res) => {
                        post(url, data)
                            .then((resp) => resolve(resp))
                            .catch((resp) => reject(resp))
                    })
                    .catch((resp) => reject(resp))
            } else {
                // 每次请求,将当前sessionTicket加入header
                app.$axios.setHeader('zsdx-session-ticket', sessionTicket)
                app.$axios.setHeader(
                    'Content-Type',
                    'application/x-www-form-urlencoded'
                )

                // 常规请求
                app.$axios
                    .$post(url, Qs.stringify(data))
                    .then((resp) => {
                        if (resp.code == 1001) {
                            console.log(1001)
                            // 重新获取sessionTicket
                            if (gettingSessionTicket) {
                                setTimeout(function() {
                                    post(url, data)
                                        .then((resp) => resolve(resp))
                                        .catch((resp) => reject(resp))
                                }, 200)
                            } else {
                                getSessionTicketRemote()
                                    .then((res) => {
                                        post(url, data)
                                            .then((resp) => resolve(resp))
                                            .catch((resp) => reject(resp))
                                    })
                                    .catch((error) => {
                                        resolve({
                                            code: -999,
                                            msg:
                                                url +
                                                'axios请求错误,重新获取ticket:' +
                                                error
                                        })
                                    })
                            }
                        } else if (resp.code == 1002) {
                            // TODO 添加登录方法, 前后端均需处理
                            console.log(1002)
                            if (!data.no_login) {
                                this.$store.commit('isLogin/SHOW_LOGIN', {
                                    type: 'login'
                                })
                            }
                            reject(new Error('需要登录'))
                        } else {
                            resolve(resp)
                        }
                    })
                    .catch(() => {
                        resolve({
                            code: -999,
                            msg:
                                url + '接口出现错误, 参数:' + Qs.stringify(data)
                        })
                        // reject(url + '接口出现错误, 参数:' + Qs.stringify(data))
                    })
            }
        })
    }

    function upload(url, data, noTicket = false, options = {}) {
        return new Promise((resolve, reject) => {
            if (gettingSessionTicket) {
                setTimeout(function() {
                    upload(url, data, noTicket)
                        .then((resp) => resolve(resp))
                        .catch((resp) => reject(resp))
                }, 200)
                return
            }
            getSessionTicketLocal()
            // ticket空则重新获取,成功后重新请求
            if (!sessionTicket) {
                getSessionTicketRemote()
                    .then((res) => {
                        upload(url, data, noTicket)
                            .then((resp) => resolve(resp))
                            .catch((resp) => reject(resp))
                    })
                    .catch((resp) => reject(resp))
            } else {
                // 每次请求,将当前sessionTicket加入header
                app.$axios.setHeader(
                    'zsdx-session-ticket',
                    noTicket ? null : sessionTicket
                )
                app.$axios.setHeader(
                    'Content-Type',
                    'application/x-www-form-urlencoded'
                )

                // 常规请求
                const currAjax = app.$axios
                    .$post(url, data, {
                        timeout: 0,
                        onUploadProgress(e) {
                            if (e.total > 0) {
                                e.percent = (e.loaded / e.total) * 100
                            }
                            if (options.onUploadProgress) {
                                options.onUploadProgress(e, currAjax)
                            }
                        },
                        cancelToken: new axios.CancelToken(function(cancel) {
                            if (options.cancelToken) {
                                options.cancelToken(cancel)
                            }
                        })
                    })
                    .then((resp) => {
                        if (resp.code == 1001) {
                            console.log(1001)
                            // 重新获取sessionTicket
                            if (gettingSessionTicket) {
                                setTimeout(function() {
                                    upload(url, data, noTicket)
                                        .then((resp) => resolve(resp))
                                        .catch((resp) => reject(resp))
                                }, 200)
                            } else {
                                getSessionTicketRemote()
                                    .then((res) => {
                                        upload(url, data, noTicket)
                                            .then((resp) => resolve(resp))
                                            .catch((resp) => reject(resp))
                                    })
                                    .catch((error) => {
                                        resolve({
                                            code: -999,
                                            msg:
                                                url +
                                                'axios请求错误,重新获取ticket:' +
                                                error
                                        })
                                    })
                            }
                        } else if (resp.code == 1002) {
                            // TODO 添加登录方法, 前后端均需处理
                            console.log(1002)
                            if (!data.no_login) {
                                this.$store.commit('isLogin/SHOW_LOGIN', {
                                    type: 'login'
                                })
                            }
                            reject(new Error('需要登录'))
                        } else {
                            resolve(resp)
                        }
                    })
                    .catch(() => {
                        resolve({
                            code: -999,
                            msg:
                                url + '接口出现错误, 参数:' + Qs.stringify(data)
                        })
                        // reject(url + '接口出现错误, 参数:' + Qs.stringify(data))
                    })
            }
        })
    }

    // 注入方法等,通过this.$ app.$
    inject('post', post)
    inject('upload', upload)
    inject('clearSessionTicket', clearSessionTicket)
    inject('getSessionTicket', getSessionTicket)
    inject('setSessionTicket', setSessionTicket)
}
